<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片分类 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addCateBtn">添加分类</el-button>
        </el-col>
      </el-row>
      <tree-table :data='cateList' :columns='columns' :stripe='false' :selection-type='false' :show-row-hover='false'
        :expand-type='false' :show-index='true' index-text='#'>
        <!-- //是否有效 -->
        <template slot="isOk" slot-scope="scope">
          <i style="color:lightgreen;" class="el-icon-success" v-if="scope.row.cat_deleted === false"></i>
          <i style="red" class="el-icon-error" v-else></i>
        </template>
        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level === 1">二级</el-tag>
          <el-tag type="warning" v-else>三级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="operation" slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="editCateBtn(scope.row.cat_id)">编辑</el-button>
          <el-button @click="deleteCateBtn(scope.row.cat_id)" type="danger" icon="el-icon-delete" size="mini">删除</el-button>
        </template>
      </tree-table>
    </el-card>
    <!-- 分页 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum" :page-sizes="pageSizes" :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper" :total="totalDate">
    </el-pagination>
    <!-- 添加分类Dialog区域 -->
    <el-dialog @close='clearDialogData' title="添加分类" :visible.sync="isCateDialogShow" width="40%">
      <!-- 表单 -->
      <el-form :model="addCateListFrom" :rules="addCateListFromRules" ref="addCateListFromRef">
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="addCateListFrom.cat_name"></el-input>
        </el-form-item>
        <!-- 多层级联选择器 -->
        <el-form-item label='父级分类：'>
          <el-cascader :clearable='true' v-model="selectKey" :options="parentCateCascader" :props="options"
            @change="cascaderCateChange" :change-on-select='true'>
          </el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isCateDialogShow = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改分类区域 -->
    <el-dialog @close='clearForm' title="修改分类" :visible.sync="editCateDialogVisible" width="40%">
      <el-form :model="editCateForm" :rules="editCateFormRules" ref="editCateFormRef" label-width="100px">
        <el-form-item label="修改分类" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCateConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data: function () {
    return {
      // 表格数据
      cateList: [],
      // 初始查询参数
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 总数据条数
      totalDate: 0,
      pageSizes: [1, 3, 5, 10, 30],
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          prop: 'cat_deleted',
          type: 'template',
          template: 'isOk'
        },
        {
          label: '排序',
          prop: 'cat_level',
          type: 'template',
          template: 'order'
        },
        {
          label: '操作',
          type: 'template',
          template: 'operation'
        }
      ],
      isCateDialogShow: false,
      // 级联选择器默认数据
      addCateListFrom: {
        cat_pid: 0,
        cat_level: 0
      },
      addCateListFromRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 2, max: 8, message: '请输入2~8个字符之间', trigger: 'blur' }
        ]
      },
      // 级联数据
      parentCateCascader: [],
      // 级联数据的配置
      options: {
        label: 'cat_name',
        children: 'children',
        value: 'cat_id',
        expandTrigger: 'hover'
      },
      selectKey: [],
      // 显示修改对话框属性
      editCateDialogVisible: false,
      // 修改分类数据源
      editCateForm: {
        cat_name: ''
      },
      // 需改分类表单数据验证规则
      editCateFormRules: {
        cat_name: [
          { required: true, message: '请输入分类', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取页面数据
    async getCateList () {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return
      this.totalDate = res.data.total
      this.cateList = res.data.result
    },
    // 修改每页显示数据条数，触发
    handleSizeChange (val) {
      this.queryInfo.pagesize = val
      this.getCateList()
    },
    // 修改当前页码，触发事件
    handleCurrentChange (val) {
      this.queryInfo.pagenum = val
      this.getCateList()
    },
    // 添加分类按钮
    addCateBtn () {
      this.getCascaderCateList()
      this.isCateDialogShow = true
    },
    async getCascaderCateList () {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 }
      })
      this.parentCateCascader = res.data
      console.log(this.parentCateCascader)
    },
    // 更改了值，cascader就发生了变化
    cascaderCateChange () {
      if (this.selectKey.length > 0) {
        this.addCateListFrom.cat_pid = this.selectKey[this.selectKey.length - 1]
        this.addCateListFrom.cat_level = this.selectKey.length
      } else {
        this.addCateListFrom.cat_pid = 0
        this.addCateListFrom.cat_level = 0
      }
    },
    // 清除dialog数据
    clearDialogData () {
      this.$refs.addCateListFromRef.resetFields()
      this.selectKey = []
      this.addCateListFrom.cat_pid = 0
      this.addCateListFrom.cat_level = 0
    },
    // 添加分类，送往数据库
    addCate () {
      this.$refs.addCateListFromRef.validate(async (vali) => {
        if (!vali) return
        const { data: res } = await this.$http.post(
          'categories',
          this.addCateListFrom
        )
        if (res.meta.status !== 201) return this.$message.error('添加分类失败')
        this.$message.success('添加分类成功')
        this.getCateList()
        this.isCateDialogShow = false
      })
    },
    // 需改分类按钮，弹出dialog对话框
    async editCateBtn (id) {
      const { data: res } = await this.$http.get('categories/' + id)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('修改分类失败')
      this.editCateForm = res.data
      this.editCateDialogVisible = true
    },
    // 关闭dialog清除修改对话框的数据
    clearForm () {
      this.$refs.editCateFormRef.resetFields()
    },
    // 确认修改分类数据按钮
    editCateConfirm () {
      this.$refs.editCateFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('categories/' + this.editCateForm.cat_id, {
          cat_name: this.editCateForm.cat_name
        })
        if (res.meta.status !== 200) return this.$message.error('修改分类失败')
        this.$message.success('修改分类成功')
        this.getCateList()
        this.editCateDialogVisible = false
      })
    },
    // 删除分类按钮
    async deleteCateBtn (id) {
      const confirm = await this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)
      if (confirm !== 'confirm') return this.$message.info('删除分类取消成功')
      // 真的要删除分类了
      const { data: res } = await this.$http.delete('categories/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除分类失败')
      this.$message.success('删除分类成功')
      this.getCateList()
    }
  }
}
</script>
<style lang="less" scoped>
.el-breadcrumb {
  margin-bottom: 15px;
}
.el-button {
  margin-bottom: 10px;
}
.el-cascader {
  div {
    height: 300px;
  }
  width: 100%;
}
</style>
